import 'dart:collection';

import 'package:flutter/foundation.dart';
import 'package:garbage_classification/utils/request.dart';
import 'package:garbage_classification/utils/sqlite_util.dart';

class MainManager with ChangeNotifier {
  static MainManager instance = MainManager();
  List historyList = [];
  List resouList = [];
  final sqliteUtil = SqliteUtil();

  void init() async {
    getResou();
    sqliteUtil.createDb(1);
    refresh();
  }

  void getResou() async {
    try {
      var res = await getResouKey();
      resouList = res['resouList'].toList();
      notifyListeners();
    } catch (e) {}
  }

  Future queryAllKeeper() async {
    return query("select * from Classification");
  }

  void clearDb() {
    sqliteUtil.delete("DELETE FROM Classification");
  }

  Future query(sql) async {
    return sqliteUtil.query(sql);
  }

  void insert({String history = ""}) async {
    await sqliteUtil.insert(
        'INSERT INTO Classification(id,history) VALUES("1","$history")');
    refresh();
  }

  String listToString(List<String> list) {
    if (list == null) {
      return null;
    }
    String result;
    list.forEach((string) =>
        {if (result == null) result = string else result = '$result,$string'});
    return result.toString();
  }

  void update({List history}) async {
    if (history.length > 10) history.removeLast();
    await sqliteUtil.update(
        'UPDATE Classification SET history = ? WHERE id = "1"',
        [listToString(history)]);
    refresh();
  }

  void delete() async {
    await sqliteUtil.delete('DELETE FROM Classification WHERE id = "1"');
    refresh();
  }

  refresh() {
    queryAllKeeper().then((res) {
      if (res.length == 0) {
        insert(history: "");
        historyList = [];
        notifyListeners();
      } else {
        historyList = res[0]['history'].toString().split(",").toList();
        notifyListeners();
      }
    });
  }
}
